<template>
  <div class="recipe-add-or-edit">
    <!-- 食物分类下新增一栏属性介绍,用于食材属性跳转 -->
    <el-form ref="natureForm" v-model="form" label-position="left" inline class="demo-table-expand">
      <el-form-item prop="src" label="物品贴图">
        <ossUpload :imageUrl="form.src ? domain + form.src : ''" :imgName="randomName" @upload-img="handlerUpload" />
      </el-form-item>
      <el-form-item prop="name" label="中文名称">
        <el-input v-model="form.name" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="alis" label="英文名称">
        <el-input v-model="form.alis" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="tag" label="标签">
        <el-select v-model="form.tag" multiple placeholder="请选择">
          <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="composition" label="合成物">
        <CompositionItem :selectedArr.sync="form.composition" :showNum="true" :module="['foods']"
          :mid="$route.query.mid" :fixNumber="true" />
      </el-form-item>
      <el-form-item prop="createRecipe" label="可合成食谱">
        <CompositionItem :selectedArr.sync="form.createRecipe" :showNum="false" :module="['foods']"
          :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="need" label="必须材料">
        <FoodCompositionItem :selectedArr.sync="form.need" :showNum="true" :module="['foods']"
          :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="fail" label="不可添加">
        <CompositionItem :selectedArr.sync="form.fail" :showNum="true" :module="['foods']" :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="property" label="食物属性">
        <CompositionItem :selectedArr.sync="form.property" :showNum="true" :module="['foods']"
          :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="technology" label="合成条件">
        <CompositionItem :selectedArr.sync="form.technology" :showNum="false"
          :module="['materials', 'heros', 'natures']" :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="hungry" label="饱食度">
        <el-input v-model="form.hungry" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="hp" label="血量">
        <el-input v-model="form.hp" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="san" label="精神">
        <el-input v-model="form.san" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="fresh" label="保质期">
        <el-input v-model="form.fresh" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="priority" label="优先级">
        <el-input v-model="form.priority" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="cookingTime" label="烹饪时间">
        <el-input v-model="form.cookingTime" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="san" label="温度影响">
        <el-input v-model="form.temperature" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="console" label="生成代码">
        <el-input v-model="form.console" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="extraLink" label="额外链接">
        <ExtraCompositionItem :selectedArr.sync="form.extraLink" :mid="$route.query.mid" :module="module" />
      </el-form-item>
      <el-form-item prop="extraLink" label="额外属性">
        <ExtraProperty :list.sync="form.extraProperty" />
      </el-form-item>
      <mavon-editor v-model="form.introduce" @imgAdd="imgUpload" class="editor-sty" :boxShadow="false" ref="md">
      </mavon-editor>
    </el-form>
    <el-button type="primary" @click="addItem" style="margin-top: 16px">
      {{
      $route.query.type === "edit" ? "更新" : "提交"
      }}
    </el-button>
  </div>
</template>

<script>
  import ossUpload from "@/components/ossUpload.vue";
  import CompositionItem from "@/components/CompositionItem.vue";
  import FoodCompositionItem from "@/components/FoodCompositionItem.vue";
  import ExtraCompositionItem from "@/components/ExtraCompositionItem.vue";
  import ExtraProperty from "@/components/ExtraProperty.vue";
  import md5 from "md5-js";
  import OSS from "ali-oss";

  export default {
    name: "natureAddOrEdit",
    data() {
      return {
        module: ["materials", "foods", "anims", "natures", "heros"],
        configOptions: [], // 配置选择项
        options: [], // 标签选择项
        searchData: [],
        form: {
          src: "",
          name: "",
          alis: "",
          tag: [],
          hungry: "",
          hp: "",
          san: "",
          fresh: "",
          temperature: "",
          priority: "",
          cookingTime: "",
          console: "",
          introduce: "",
          composition: [],
          createRecipe: [],
          technology: [],
          property: [],
          fail: [],
          need: [],
          extraLink: [],
          extraProperty: []
        },
      };
    },
    components: {
      ossUpload,
      CompositionItem,
      FoodCompositionItem,
      ExtraCompositionItem,
      ExtraProperty
    },
    computed: {
      randomName: {
        get: function () {
          let time = new Date();
          return md5(time);
        },
        cache: false,
      },
    },
    async activated() {
      await this.getTag();
      if (this.$route.query.type === "edit") {
        this.fetchDetail();
      }
    },
    deactivated() {
      this.form = {
        src: "",
        name: "",
        alis: "",
        tag: [],
        hungry: "",
        hp: "",
        san: "",
        fresh: "",
        temperature: "",
        priority: "",
        cookingTime: "",
        console: "",
        introduce: "",
        composition: [],
        createRecipe: [],
        technology: [],
        property: [],
        fail: [],
        need: [],
        extraLink: [],
        extraProperty: []
      };
    },
    methods: {
      /**
       * 获取详情数据
       **/
      async fetchDetail() {
        let res = await this.axios.get("food/single", {
          params: {
            id: this.$route.query.id,
          },
        });
        let temp = this.showDataTransform(res.data, [
          { needNum: true, key: "composition" },
          { needNum: false, key: "createRecipe" },
          { needNum: false, key: "technology" },
          { needNum: true, key: "property" },
          { needNum: true, key: "fail" },
          { hasList: true, key: "extraLink" }
        ]);
        temp.tag = temp.tag.map((val) => {
          return val._id;
        });
        this.form = temp;
        this.form.need = this.showDataTransform2(res.data.need);
      },
      /**
       * @description 获取自然对应的标签
       */
      async getTag() {
        let res = await this.$store.dispatch("getTags", {
          kind: "foods",
          mid: this.$route.query.mid,
        });
        this.options = res;
      },
      /**
       * @description 食谱新增或修改
       */
      async addItem() {
        let [
          _composition,
          _createRecipe,
          _technology,
          _property,
          _fail,
        ] = this.transformSumbitData([
          {
            list: this.form.composition,
            needNum: true,
          },
          {
            list: this.form.createRecipe,
            needNum: false,
          },
          {
            list: this.form.technology,
            needNum: false,
          },
          {
            list: this.form.property,
            needNum: true,
          },
          {
            list: this.form.fail,
            needNum: true,
          },
        ]);
        let _need = this.transformSumbitData2(this.form.need);
        let _extraLink = this.transformSumbitDataList(this.form.extraLink)
        let requestUrl =
          this.$route.query.type === "edit" ? "/food/update" : "/food/add";
        let res = await this.axios.post(requestUrl, {
          version: this.$store.state.version,
          ...this.form,
          composition: _composition,
          createRecipe: _createRecipe,
          technology: _technology,
          property: _property,
          need: _need,
          fail: _fail,
          extraLink: _extraLink
        });
        if (!res.data.code) {
          this.$message.success("添加成功");
          this.$router.go(-1);
        }
      },
      handlerUpload(src) {
        this.form.src = src;
      },
      /**
       * 图片上传
       */
      imgUpload(filename, $file) {
        // oss配置
        const client = new OSS({
          endpoint: "oss-cn-beijing.aliyuncs.com",
          accessKeyId: "LTAI4FgrsFXo8ij335BxeRbp",
          accessKeySecret: "oG0PWkV0qOeDoJQfwEHOqIvTp16S0x",
          bucket: "stavebox",
        });
        // 图片路径拼接，dirName其实就是定义存在oss的哪个虚拟文件夹下的
        let time = new Date();
        let hash = md5(time);
        let imgType = $file.type.split("/")[1];
        let hashName = "Article/" + hash + "." + imgType;
        // 将文件流上传至oss
        client
          .put(hashName, $file)
          .then((res) => {
            let imgUrl = this.domain + res.name;
            this.$refs.md.$img2Url(filename, imgUrl);
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },
  };
</script>

<style lang="scss">
  .recipe-add-or-edit {
    .demo-table-expand {
      font-size: 0;
    }

    .demo-table-expand label {
      width: 120px;
      color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 16px;
      width: 50%;
    }
  }
</style>
<style lang="scss" scoped>
  .recipe-add-or-edit {
    padding: 16px;

    .delete-button,
    .add-button {
      display: inline-block;
      width: 60px;
      flex-shrink: 0;
    }

    .material {
      margin-bottom: 10px;
    }

    .attr-container {
      display: flex;
      height: 50px;
    }
  }
</style>